from flask import request, jsonify
from app.api import api_bp
from app.models import Project

@api_bp.route('/projects', methods=['GET'])
def get_projects():
    """获取所有项目"""
    projects = Project.query.all()
    return jsonify([project.to_dict() for project in projects])

@api_bp.route('/projects', methods=['POST'])
def create_project():
    """创建新项目"""
    data = request.get_json()
    
    if not data or not data.get('name'):
        return jsonify({'error': '项目名称不能为空'}), 400
    
    project = Project(
        name=data['name'],
        description=data.get('description', '')
    )
    
    try:
        project.save()
        return jsonify(project.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_bp.route('/projects/<int:project_id>', methods=['GET'])
def get_project(project_id):
    """获取单个项目"""
    project = Project.query.get_or_404(project_id)
    return jsonify(project.to_dict())

@api_bp.route('/projects/<int:project_id>', methods=['PUT'])
def update_project(project_id):
    """更新项目"""
    project = Project.query.get_or_404(project_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '请求数据不能为空'}), 400
    
    project.name = data.get('name', project.name)
    project.description = data.get('description', project.description)
    
    try:
        project.save()
        return jsonify(project.to_dict())
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_bp.route('/projects/<int:project_id>', methods=['DELETE'])
def delete_project(project_id):
    """删除项目"""
    project = Project.query.get_or_404(project_id)
    
    try:
        project.delete()
        return jsonify({'message': '项目删除成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500